<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2018/11/9
 * Time: 13:25
 */

namespace Order\Controller;

use Common\Controller\MemberbaseController;
use Common\Log\TypeLog;
use Order\Model\OrderModel;
use Portal\Model\PostsModel;
use Wx\Controller\WxPayController;

class OrderController extends MemberbaseController{

    protected $order_model;
    protected $page_size;

    function _initialize() {
        parent::_initialize();
        $this->page_size    = 10;
        $this->order_model  = D("Order/Order");
    }

    // 个人中心订单列表 -- 活动订单
    public function activity_lists()
    {
        // 全部订单，已支付，未支付，已取消
        $user_id    = sp_get_current_userid();
        $index      = I('status');
        $index_arr  = [1, 2, 3, 4];

        if (!in_array($index, $index_arr)) {
            $this->error('数据有误');exit;
        }
        $this->assign('list_index', $index);

        $where = array(
            'o.user_id'     => $user_id,
            'o.type'        => OrderModel::ORDER_TYPE_ACT_TICKET,
        );

        $count_index    = array();
        $f_status       = array();
        $f_refund       = array();
        foreach ($index_arr as $v) {
            if ($v == 1) {
                //全部订单
                $status = [OrderModel::ORDER_STATUS_NOT_PAY, OrderModel::ORDER_STATUS_HAS_PAY, OrderModel::ORDER_STATUS_EXPIRE, OrderModel::ORDER_STATUS_PAY_FAIL, OrderModel::ORDER_STATUS_REFUND];
                $refund = [OrderModel::ORDER_REFUND_STATUS_NORMAL, OrderModel::ORDER_REFUND_STATUS_ING, OrderModel::ORDER_REFUND_STATUS_HAS, OrderModel::ORDER_REFUND_STATUS_FAILED, OrderModel::ORDER_REFUND_STATUS_SELF];
                $btn    = '全部';
            } elseif ($v == 2) {
                //已支付
                $status = [OrderModel::ORDER_STATUS_HAS_PAY];
                $refund = [OrderModel::ORDER_REFUND_STATUS_NORMAL];
                $btn    = '已支付';
            } elseif ($v == 3) {
                //未支付
                $status = [OrderModel::ORDER_STATUS_NOT_PAY];
                $refund = [OrderModel::ORDER_REFUND_STATUS_NORMAL];
                $btn    = '未支付';
            } else {
                //已取消
                $status = [OrderModel::ORDER_STATUS_HAS_PAY, OrderModel::ORDER_STATUS_EXPIRE, OrderModel::ORDER_STATUS_PAY_FAIL, OrderModel::ORDER_STATUS_REFUND];
                $refund = [OrderModel::ORDER_REFUND_STATUS_ING, OrderModel::ORDER_REFUND_STATUS_HAS, OrderModel::ORDER_REFUND_STATUS_FAILED, OrderModel::ORDER_REFUND_STATUS_SELF];
                $btn    = '已取消';
            }

            $where['o.status']          = ['in', $status];
            $where['o.refund_status']   = ['in', $refund];
            $count_index[$v]['count']   = $this->order_model->alias('o')->where($where)->count();
            $count_index[$v]['btn']     = $btn;
            $count_index[$v]['status']  = $v;

            if ($v == $index) {
                $f_status = $status;
                $f_refund = $refund;
            }
        }

        $this->assign('count_index', $count_index);

        $where['o.status']          = ['in', $f_status];
        $where['o.refund_status']   = ['in', $f_refund];

        // 订单总数
        $count  = $this->order_model->alias('o')->where($where)->count();
        $page   = $this->page($count, $this->page_size);
        $lists  = $this->order_model
            ->alias('o')
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("o.created_at desc")
            ->select();

        foreach ($lists as $k => $v) {

            $ticket_info        = M('act_ticket')->where(['id' => $v['goods_id']])->find();
            $act_info           = M('activity')->where(['id' => $ticket_info['act_id']])->find();
            $thumb              = json_decode($act_info['thumb'], true);
            $act_status         = get_activity_status($act_info);
            if (strtotime($act_info['end_time']) > time() || empty($act_info['link_addr'])) {
                $act_info['link_addr'] = U('Activity/Activity/activity_info', ['id' => $act_info['id']]);
            }
            $v['link_addr']     = $act_info['link_addr'];
            $v['img']           = sp_get_asset_upload_path($thumb['thumb']);
            $v['city_name']     = get_city_name_by_id($act_info['city_id']);
            $v['act_name']      = $act_info['name'];
            $v['start_time']    = date("m.d H:i", strtotime($act_info['start_time']));
            $v['end_time']      = date("m.d H:i", strtotime($act_info['end_time']));
            $v['act_status']    = $act_status;
            $v['sub_menu']      = $this->_get_order_status($act_info, $v);

            $lists[$k] = $v;
        }

        // 用户是否登录并且有oa_openid
        $get_base_info = false;
        $user = sp_get_current_user();
        if ($user && !$user['oa_openid']) {
            $get_base_info = true;
        }
        $this->assign('get_base_info', $get_base_info);

        // 二维码
        $file_name  = "activity_order_refund";
        $url        = 'http://' . C('DOMAIN_NAME') . U('Order/Order/activity_lists', ['status' => 1]);
        $path       = get_link_qrcode_path($file_name, $url);
        $this->assign('refund_qrcode', $path);

        $this->assign("page", $page->show('default'));
        $this->assign("lists", $lists);
        $this->assign("total_page", ceil($count / $this->page_size));
        $this->display();
    }

    // 个人中心订单列表 -- 问答订单
    public function question_lists()
    {
        $user_id    = sp_get_current_userid();
        $where      = array(
            'o.user_id'         => $user_id,
            'o.type'            => OrderModel::ORDER_TYPE_QUESTION,
            'o.status'          => OrderModel::ORDER_STATUS_HAS_PAY,
            'p.post_status'     => PostsModel::POST_STATUS_NORMAL,
            'p.post_type'       => PostsModel::POST_TYPE_DISCUSSION_QUESTION,
        );
        $count      = $this->order_model->alias('o')->join("__POSTS__ p on p.id = o.goods_id")->where($where)->count();
        $page       = $this->page($count, $this->page_size);
        $lists      = $this->order_model
            ->alias('o')
            ->join("__POSTS__ p on p.id = o.goods_id")
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("o.created_at desc")
            ->field('o.*, p.post_title')
            ->select();

        $this->assign('count', $count);
        $this->assign("page", $page->show('default'));
        $this->assign("lists", $lists);
        $this->assign("total_page", ceil($count / $this->page_size));
        $this->display();
    }

    // 课程专题订单
    public function lesson_lists()
    {
        $user_id    = sp_get_current_userid();
        $where      = array(
            'o.user_id'         => $user_id,
            'o.type'            => OrderModel::ORDER_TYPE_LESSON,
            'o.status'          => OrderModel::ORDER_STATUS_HAS_PAY,
        );
        $count      = $this->order_model->alias('o')->join("__LESSON_SUBJECT__ l on l.id = o.goods_id", 'left')->where($where)->count();
        $page       = $this->page($count, $this->page_size);
        $lists      = $this->order_model
            ->alias('o')
            ->join("__LESSON_SUBJECT__ l on l.id = o.goods_id", 'left')
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("o.created_at desc")
            ->field('l.subject_img, l.subject_name, l.id')
            ->select();

        $this->assign('count', $count);
        $this->assign("page", $page->show('default'));
        $this->assign("lists", $lists);
        $this->assign("total_page", ceil($count / $this->page_size));
        $this->display();
    }

    // 订单 退票/退款
    public function order_refund()
    {
        $id         = I('id');
        $now        = time();
        $user_id    = sp_get_current_userid();
        $order_info = $this->order_model->where(['id' => $id, 'user_id' => $user_id])->find();
        if ($order_info && $order_info['type'] == OrderModel::ORDER_TYPE_ACT_TICKET) {

            $ticket_info    = M('act_ticket')->where(['id' => $order_info['goods_id']])->find();
            $act_info       = M('activity')->where(['id' => $ticket_info['act_id']])->find();

            if ($act_info && strtotime($act_info['start_time']) > $now && strtotime($act_info['refund_ticket_time']) > $now && strtotime($act_info['buy_ticket_time']) < $now) {
                if ($order_info['status'] == OrderModel::ORDER_STATUS_NOT_PAY) {
                    // 取消订单
                    $this->order_model->order_refund($id, $order_info['goods_id'], $order_info['goods_num']);

                } elseif ($order_info['status'] == OrderModel::ORDER_STATUS_HAS_PAY && $order_info['exchange'] == 0 && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_NORMAL) {
                    $refund_reason = I('refund_reason');
                    if (!$refund_reason) {
                        $this->error('请填写退款原因');exit;
                    }

                    $user = sp_get_current_user();
                    if (empty($user['oa_openid'])) {
                        session('user', null);
                        $this->error('请在微信客户端中使用微信登录，我们将退款到您的微信中~', U('User/Login/index', ['redirect' => base64_encode($_SERVER['REQUEST_URI'])]));
                    }

                    // 退款申请
                    $this->order_model->where(['id' => $id])->save(['refund_status' => OrderModel::ORDER_REFUND_STATUS_ING, 'refund_reason' => $refund_reason]);
                }
                $this->success('操作成功');
            } else {
                $this->error('超出退票时间');exit;
            }
        } else {
            $this->error('订单信息有误');exit;
        }
    }

    // 扫描票的二维码
    public function order_exchange()
    {
        $id         = I('id');      // 订单id
        $code       = I('code');    // 后台生成的兑票码
        $where      = ['id' => $id, 'status' => OrderModel::ORDER_STATUS_HAS_PAY, 'exchange' => 0, 'refund_status' => OrderModel::ORDER_REFUND_STATUS_NORMAL];
        $order_info = $this->order_model->where($where)->find();
        if ($order_info && $order_info['type'] == OrderModel::ORDER_TYPE_ACT_TICKET) {

            $ticket_info    = M('act_ticket')->where(['id' => $order_info['goods_id']])->find();
            $act_info       = M('activity')->where(['id' => $ticket_info['act_id']])->find();
            $this->assign('ticket_info', $ticket_info);
            $this->assign('act_info', $act_info);

            if ($code) {
                // 兑换
                if ($code == $act_info['ticket_code']) {
                    // 修改订单的状态
                    $this->order_model->where(['id' => $id])->save(['exchange' => 1]);
                    // 添加日志
                    TypeLog::addNormalLog(sp_get_current_userid(), $order_info['user_id'], TypeLog::LOG_TYPE_EXCHANGE_ACT_TICKET, $id);
                    $this->assign('exchange', 1);
                    $this->display();
                } else {
                    $this->error('兑换码错误');
                }
            } else {
                // 扫码
                $this->display();
            }
        }
    }

    // 移动端端我的订单 -- 二级菜单页
    public function mobile_order_sub_menu()
    {
        $this->display();
    }


    // 获取订单状态
    private function _get_order_status($act_info, $order_info) {
        $now = time();

        if (strtotime($act_info['buy_ticket_time']) < $now
            && strtotime($act_info['start_time']) > $now
            && $order_info['status'] == OrderModel::ORDER_STATUS_NOT_PAY
            && $order_info['exchange'] == 0
            && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_NORMAL
            && $order_info['created_at'] + OrderModel::ORDER_EXPIRE_TIME > $now)
        {
            $status['pay']['status']            = 1;
            $status['pay']['msg']               = '去付款';

            $status['cancel_order']['status']   = 1;
            $status['cancel_order']['msg']      = '取消订单';
        }

        if (strtotime($act_info['refund_ticket_time']) > $now
            && strtotime($act_info['buy_ticket_time']) < $now
            && $order_info['status'] == OrderModel::ORDER_STATUS_HAS_PAY
            && $order_info['exchange'] == 0
            && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_NORMAL)
        {
            $status['refund_order']['status']   = 1;
            $status['refund_order']['msg']      = '退票退款';
        }

        if (strtotime($act_info['end_time']) > $now
            && strtotime($act_info['buy_ticket_time']) < $now
            && $order_info['status'] == OrderModel::ORDER_STATUS_HAS_PAY
            && $order_info['exchange'] == 0
            && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_NORMAL)
        {
            $status['exchange']['status']   = 1;
            $status['exchange']['msg']      = '兑换票';
        }

        if (strtotime($act_info['buy_ticket_time']) < $now
            && $order_info['status'] == OrderModel::ORDER_STATUS_HAS_PAY
            && $order_info['exchange'] == 0
            && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_ING)
        {
            $status['refund_check']['status']   = 1;
            $status['refund_check']['msg']      = '退款审核中';
        }

        if (strtotime($act_info['buy_ticket_time']) < $now
            && $order_info['status'] == OrderModel::ORDER_STATUS_HAS_PAY
            && $order_info['exchange'] == 1
            && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_NORMAL)
        {
            $status['has_exchange']['status']   = 1;
            $status['has_exchange']['msg']      = '已出票';
        }

        if (strtotime($act_info['buy_ticket_time']) < $now
            && $order_info['status'] == OrderModel::ORDER_STATUS_HAS_PAY
            && $order_info['exchange'] == 0
            && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_HAS)
        {
            $status['has_refund']['status']   = 1;
            $status['has_refund']['msg']      = '已退款';
        }

        if (strtotime($act_info['buy_ticket_time']) < $now
            && $order_info['status'] == OrderModel::ORDER_STATUS_HAS_PAY
            && $order_info['exchange'] == 0
            && $order_info['refund_status'] == OrderModel::ORDER_REFUND_STATUS_FAILED)
        {
            $status['refund_fail']['status']   = 1;
            $status['refund_fail']['msg']      = '审核失败';
        }

        return $status;
    }
}

